﻿using Midi;
using System.Diagnostics.Contracts;
using Microsoft.Pex.Framework;

namespace AutomaTones.HW_Sense_Compute {
    /// <summary>
    /// Starts sensing the incoming Midi messages and forwards these messages, which is handled by ComputeLaunchpad.
    /// This class is part of the Hardware, Sense, Compute Pattern.
    /// </summary>
    /// <author>Anders Bech Mellson, anbh@itu.dk</author>
    [PexClass]
    class SenseLaunchpad : ISense {
        private readonly InputDevice _launchpadIn;
        public readonly ComputeLaunchpad ComputeLaunchpad;

        /// <summary>
        /// Creates a connection to the Launchpad.
        /// </summary>
        public SenseLaunchpad() {
            Contract.Requires(!ConnectLaunchpad.In.IsOpen);
            _launchpadIn = ConnectLaunchpad.In;
            _launchpadIn.Open();
            _launchpadIn.NoteOn += PadPressed;
            _launchpadIn.ControlChange += ControlButtonPressed;
            ComputeLaunchpad = new ComputeLaunchpad();
        }

        /// <summary>
        /// Starts sensing on the connected Launchpad.
        /// </summary>
        [PexMethod]
        public void StartSensing() {
            _launchpadIn.StartReceiving(null);
        }

        /// <summary>
        /// Sends a NoteOnMessage to ComputeLaunchpad.
        /// </summary>
        /// <param name="msg"></param>
        private void PadPressed(NoteOnMessage msg) {
            ComputeLaunchpad.Compute(msg);
        }

        /// <summary>
        /// Sends a ControlChangeMessage to ComputeLaunchpad.
        /// </summary>
        /// <param name="msg"></param>
        private void ControlButtonPressed(ControlChangeMessage msg) {
            ComputeLaunchpad.ControlButton(msg);
        }
    }
}
